package SSU;

import SSU.Exceptions.*;

public class ListVector implements Vector {

    private Node beforeFirst = new Node();
    private int length = 0;

    public ListVector() {
    }

    public ListVector(int n) {
        length = n;
        Node it = beforeFirst;
        for (int i = 0; i < n; i++) {
            it.next = new Node();
            it = it.next;
        }
    }
    
    public ListVector(double[] elements) {
        length = elements.length ;
        Node it = beforeFirst;
        for (int i = 0; i < elements.length; i++) {
            it.next = new Node(elements[i]);
            it = it.next;
        }
    }

    @Override
    public double get(int index) {
        if (index < 0 || index >= size())
            throw new IndexException("Index: " + index);
        Node it = beforeFirst;
        for (int i = 0; i <= index; i++) {
            it = it.next;
        }
        return it.value;
    }

    @Override
    public void set(int index, double value) {
        if (index < 0 || index >= size())
            throw new IndexException("Index: " + index);
        Node it = beforeFirst;
        for (int i = 0; i <= index; i++) {
            it = it.next;
        }
        it.value = value;
    }

    @Override
    public int size() {
        return length;
    }
    /**
     * Adds new element at index
     * @param index of element to put new element
     * @param value of new elemenet
     */
    public void add(int index, double value) {
       if (index < 0 || index >= size())
            throw new IndexException("Index: " + index);
        Node it = beforeFirst, tmp;
        for (int i = 0; i < index; i++) {
            it = it.next;
        }
        tmp = it.next;
        it.next = new Node(value);
        it.next.next = tmp;
    }
    /**
     * Deletes element by index
     * @param index of element to delete
     */
    public void delete(int index) {
        Node it = beforeFirst, tmp;
        for (int i = 0; i < index; i++) {
            it = it.next;
        }
        it.next = it.next.next;
    }
}

class Node{
    double value;
    Node next;
    public Node(){
    }
    public Node(double value){
        this.value = value;
    }
}